<?php

namespace App\Http\Controllers\Admin;

use App\Admin\ClientCode;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Client;
use DB;

class ClientController extends Controller
{
    //客户列表展示
    public function index(Request $request)
    {
        if ($request->expectsJson()) {
            $client = new Client();
            $result = $client->getTableData($request->all(), null, ['id', 'desc'], null);
            return response()->json($result);
        } else {
            return view('admin.client.index');
        }
    }

    //展示添加客户信息的二维码
    public function showQrCode(Request $request)
    {

        return view('admin.client.showQrCode');
    }

    //客户删除
    public function del(Request $request)
    {

        $id = $request->id;

        //  delete 返回受影响的行数
        $result = Client::where('id', $id)->delete();
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $result >= 0 ?  '1'
            : '0';
    }

    //客户添加
    public function add(Request $request)
    {
        if ($request->isMethod('POST')) {
            $post_data = $request->only(['name', 'contact', 'telephone', 'address','entrusted_company','name_ABC','gqj_ID']);
            //插入数据    insert 返回true 或 false
            $result = Client::insert($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        } else {
            $enable_tool_ID = DB::table('setting')->where('id', '1')->value('enable_tool_ID');
            $clientcodes = ClientCode::get()->toArray();
            $clientcodes = list_to_tree($clientcodes);
            return view('admin.client.add',compact('enable_tool_ID','clientcodes'));
        }
    }

    //客户自己添加
    public function addSelf(Request $request)
    {
        if ($request->isMethod('POST')) {
            $post_data = $request->only(['name', 'contact', 'telephone', 'address','entrusted_company']);
            //插入数据    insert 返回true 或 false
            $result = Client::insert($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        } else {
            $name_rep = DB::table('setting')->where('id', '1')->value('name_rep');
            return view('admin.client.addSelf', compact('name_rep'));
        }
    }
    //客户自己添加成功后跳转到此页面
    public function addSucc()
    {
        return view('admin.client.addSucc');
    }

    //客户修改
    public function edit(Request $request)
    {
        $id = $request->id;
        if ($request->isMethod('POST')) {
            $post_data = $request->only(['name', 'contact', 'telephone', 'address','entrusted_company','name_ABC','gqj_ID']);
            //update 返回受影响的行数
            $result = Client::where('id', $id)->update($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result >= 0 ? '1' : '0';
        } else {
            $data = Client::find($id);

            if ($data) {
                //查到了结果
                $enable_tool_ID = DB::table('setting')->where('id', '1')->value('enable_tool_ID');
                return view('admin.client.edit', compact('data','enable_tool_ID'));
            } else {
                //未查到结果
                $error_title = '';
                $error_description = '当前记录已经删除 ~';

                $js = <<<eof
                    <script type="text/javascript">
                        parent.table_reload(0);//0停留在当前页，1回到第一页
                    </script>
eof;
                echo view('errors.error', compact('error_title', 'error_description'));
                return $js;
            }
        }
    }

    /* 合同概要信息展示 */
    public function add_gqj(Request $request)
    {
        $client_id = $request->id;
        $client_info = DB::table('a_client')->where('id', $client_id)->first();

        $tool_info = DB::table('a_tool')->where('ishide', '0')->orderBy('stamp', 'stamp')->get();
        $data = DB::table('a_client as a')
            ->leftJoin('a_gqj as b', 'a.id', '=', 'b.client_id')
            ->where('b.status', '<>',2)
            ->select('a.*', 'b.*')
            ->orderBy('b.id', 'asc')->distinct()->get();
        $factorys = DB::table('a_factory')->orderBy('sort', 'desc')->pluck('name');
        $places = DB::table('setting_sys')->where('key', 'test_place')->value('value');
        $places = $places ? explode(',', $places) : '';
        return view('admin.client.add_gqj', compact('client_info', 'tool_info', 'data','factorys','places'));
    }

    /* 合同概要信息添加 */
    public function insert_gqj(Request $request) {
        //请求为 ajax
        if($request->expectsJson()) {
            $data = $request->only(['client_id', 'client_name','tool_id', 'vol_id', 'class_id', 'class','std_id', 'bar_code', 'self_num', 'manufacturer', 'production_date', 'guige_xinghao','brand', 'sample_status', 'place','force_scrap_date']);
            $items = $request->items;
            //项目id
            $data['item_ids'] = implode(',', $items); //1,2,3,4  数组变字符串
            //项目名称
            $arr_item_names = DB::table('a_testitem')->whereIn('id', $items)->orderBy(DB::raw("field(id,{$data['item_ids']})"))->pluck('name');
            $data['item_names'] = implode("，", $arr_item_names->toArray()); //此处是中文 逗号
            // 如果额定电压id为 0
            if($data['vol_id'] === '0') {
                $data['voltage'] = '/';
            }
            else {
                $data['voltage'] = DB::table('a_voltage_class')->where('id', $data['vol_id'])->value('val');
            }
            // 如果分类id为 0
            if($data['class_id'] === '0') {
                $data['class'] = '/';
            } else {
                $data['voltage_class'] = DB::table('a_voltage_class')->where('id', $data['class_id'])->value('val');
            }
            $data['voltage_class_id'] = $data['class_id'];
            unset($data['class']);
            unset($data['class_id']);
            //标准代号
            $data['std_num'] = DB::table('a_standard')->where('id', $data['std_id'])->value('num');
            //样品信息
            $tool_info = DB::table('a_tool')->where('id', $data['tool_id'])->first();
            //样品名称
            $data['tool_name'] = $tool_info->name;
            //样品单位
            $data['unit'] = $tool_info->unit;
            //dd($data);
            $a_gqj_id = DB::table('a_gqj')->insertGetId($data);
            if ($a_gqj_id) {
                return '1';
            }else{
                return '添加失败';
            }
        }
    }

    public function gqj_del(Request $request) {
        $id = $request->input('id');
        //交给模型处理数据  delete 返回受影响的行数
        $result = DB::table('a_gqj')->where('id', $id)->delete();
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $result >= 0 ? '1' : '0';
    }

    //客户选择
    // public function select(Request $request)
    // {
    //     $data = Client::get();
    //     return view('admin.client.select', compact('data'));
    // }

    //获取客户信息
    public function getClientInfo(Request $request)
    {
        $id = $request->id;
        $data = Client::find($id);
        $result = $data ? $data : "-1";
        return response()->json($result);
    }

    //根据送检单位的中文获取英文首字母
    public function getABC(Request $request)
    {
        $str = $request->str;
        return $this->getAllCharter($str);
    }

    /**
     * php获取 多个中文字符 拼音首字母
     */
    private function getAllCharter($str)
    {
        $res = "";
        $str_len = iconv_strlen($str,"UTF-8");
        for ($i=0; $i < $str_len; $i++) {
            # code...
            $char = mb_substr($str, $i, 1);
            $A = $this->getFirstCharter($char);
            $A = $A === 0 ? '*' : $A;
            $res .= $A;
        }
        return $res;
    }

    /**
     * php获取 一个中文字符 拼音首字母
     */
    private function getFirstCharter($str)
    {
        if (empty($str)) {
            return 0;
        }

        try {
            $str = mb_substr($str, 0, 1);
            $fchar = ord($str{0});
            if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
            $s1 = iconv('UTF-8', 'GBK//TRANSLIT//IGNORE', $str);
            $s2 = iconv('GBK', 'UTF-8//TRANSLIT//IGNORE', $s1);
            $s = $s2 == $str ? $s1 : $str;
            if (!isset($s{1}) || !isset($s{0})){
                return 0;
            }
            $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
            if ($asc >= -20319 && $asc <= -20284) return 'A';
            if ($asc >= -20283 && $asc <= -19776) return 'B';
            if ($asc >= -19775 && $asc <= -19219) return 'C';
            if ($asc >= -19218 && $asc <= -18711) return 'D';
            if ($asc >= -18710 && $asc <= -18527) return 'E';
            if ($asc >= -18526 && $asc <= -18240) return 'F';
            if ($asc >= -18239 && $asc <= -17923) return 'G';
            if ($asc >= -17922 && $asc <= -17418) return 'H';
            if ($asc >= -17417 && $asc <= -16475) return 'J';
            if ($asc >= -16474 && $asc <= -16213) return 'K';
            if ($asc >= -16212 && $asc <= -15641) return 'L';
            if ($asc >= -15640 && $asc <= -15166) return 'M';
            if ($asc >= -15165 && $asc <= -14923) return 'N';
            if ($asc >= -14922 && $asc <= -14915) return 'O';
            if ($asc >= -14914 && $asc <= -14631) return 'P';
            if ($asc >= -14630 && $asc <= -14150) return 'Q';
            if ($asc >= -14149 && $asc <= -14091) return 'R';
            if ($asc >= -14090 && $asc <= -13319) return 'S';
            if ($asc >= -13318 && $asc <= -12839) return 'T';
            if ($asc >= -12838 && $asc <= -12557) return 'W';
            if ($asc >= -12556 && $asc <= -11848) return 'X';
            if ($asc >= -11847 && $asc <= -11056) return 'Y';
            if ($asc >= -11055 && $asc <= -10247) return 'Z';

            return 0;
        }catch (\Throwable $th) {
            return 0;
        }
    }
}
